package com.hst.capacity.facade.rest;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.hst.capacity.application.biz.DriverBiz;
import com.hst.capacity.application.biz.JobPlatformBiz;
import com.hst.capacity.application.biz.MiniProgramBiz;
import com.hst.capacity.domain.common.constants.Constants;
import com.hst.capacity.domain.exception.BusinessException;
import com.hst.capacity.domain.model.request.driver.*;
import com.hst.capacity.domain.model.response.DefaultVO;
import com.hst.capacity.domain.model.response.driver.DriverBandCarVO;
import com.hst.capacity.domain.service.UploadService;
import com.hst.capacity.infra.util.StringUtil;
import com.qiniu.storage.model.DefaultPutRet;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.util.*;

import static com.hst.capacity.domain.model.response.DefaultVO.success;

/**
 * 司机运营模块Controller，包括司机CRUD，检索等。
 */
@Slf4j
@RequestMapping("/driver")
@RestController
public class DriverController {

    @Autowired
    private JobPlatformBiz jobPlatformBiz;

    @Autowired
    private DriverBiz driverBiz;

    @Autowired
    private UploadService uploadService;

    @Autowired
    private MiniProgramBiz miniProgramBiz;

    /**
     * 创建司机信息
     *
     * @param param
     * @return
     */
    @PostMapping("/add")
    private DefaultVO add(@RequestBody @Valid DriverAddParam param, MultipartFile[] multipartFiles) {
        HashMap<String, String> returns = new HashMap<>();
        returns.put("idDriver",driverBiz.add(param,multipartFiles));
        return success(returns);
    }

    /**
     * 司机绑定车辆
     *
     * @param param
     * @return
     */
    @PostMapping("/band/vehicle")
    private DefaultVO driverBandVehicle(@RequestBody @Valid DriverBandCarParam param) {
        return success(driverBiz.driverBandVehicle(param));
    }

    /**
     * 司机解绑
     *
     * @param param
     * @return
     */
    @PostMapping("/device/unband")
    private DefaultVO deviceUnband(@RequestBody @Valid Map<String,String> param) {
        String idDriver = param.get("idDriver");
        if (StrUtil.isEmpty(idDriver))
            throw new BusinessException(4001,"司机ID[idDriver]不能为空");
        return success(driverBiz.deviceUnband(idDriver));
    }

    /**
     * 司机绑定车辆
     *
     * @param param
     * @return
     */
    @PostMapping("/location")
    private DefaultVO driverLocation(@RequestBody Map<String,String> param) {
        String idDriver = param.get("idDriver");
        if (StrUtil.isEmpty(idDriver))
            throw new BusinessException(4001,"司机ID[idDriver]不能为空");
        return success(driverBiz.driverLocation(idDriver));
    }

    /**
     * 司机解绑车辆
     *
     * @param param
     * @return
     */
    @PostMapping("/unband/vehicle")
    private DefaultVO driverUnBandVehicle(@RequestBody @Valid DriverUnBandCarParam param) {
        return success(driverBiz.driverUnBandVehicle(param));
    }

    /**
     * 司机信息分页条件检索
     *
     * @param param
     * @return
     */
    @PostMapping("/search")
    private DefaultVO search(@RequestBody @Valid DriverSearchParam param) {
        param.setCarTypeList();
        log.info("DriverSearchParam carTypeList："+ param.getCarTypes());
        return success(driverBiz.search(param));
    }

    /**
     * 待审核司机信息分页条件检索
     *
     * @param param
     * @return
     */
    @PostMapping("/pending/approval/search")
    private DefaultVO pendingApprovalSearch(@RequestBody @Valid DriverSearchParam param) {
        param.setLineFlg(0);
        param.setCarTypeList();
        param.setStatusArr(String.valueOf(Constants.DriverStatus.AUDIT));
        return success(driverBiz.search(param));
    }

    /**
     * 司机审核通过
     *
     * @param param
     * @return
     */
    @PostMapping("/review")
    private DefaultVO review(@RequestBody @Valid Map<String,String> param) {
        String idDriver = param.get("idDriver");
        if (StrUtil.isEmpty(idDriver))
            throw new BusinessException(4001,"司机ID[idDriver]不能为空");

        if (driverBiz.review(idDriver))
            return success(MapUtil.builder("success","司机审核通过").build());
        else
            return success(MapUtil.builder("success","司机审核失败").build());
    }

    /**
     * 站点驳车司机
     *
     * @param param
     * @return
     */
    @PostMapping("/stp/search")
    private DefaultVO stpSearch(@RequestBody @Valid DriverSearchParam param) {
        param.setStatusArr(param.getStatus());
        return success(driverBiz.stpSearch(param));
    }

    /**
     * 城际线路司机
     *
     * @param param
     * @return
     */
    @PostMapping("/cityline/search")
    private DefaultVO cityLineSearch(@RequestBody @Valid DriverSearchParam param) {
        param.setStatusArr(param.getStatus());
        return success(driverBiz.cityLineSearch(param));
    }

    /**
     * 订单池司机
     *
     * @param param
     * @return
     */
    @PostMapping("/orderpool/search")
    private DefaultVO orderPoolSearch(@RequestBody @Valid DriverSearchParam param) {
        param.setStatusArr(param.getStatus());
        return success(driverBiz.orderPoolSearch(param));
    }

    /**
     * 获取司机绑定车辆信息
     * @param param
     * @return
     */
    @PostMapping("/list/vehicle")
    private DefaultVO driverListVehicle(@RequestBody Map<String,String> param){
        String idDriver = param.get("idDriver");
        if (StrUtil.isEmpty(idDriver))
            throw new BusinessException(4001,"司机ID[idDriver]不能为空");
        DriverBandCarVO vo = driverBiz.driverListVehicle(idDriver);
        ArrayList<DriverBandCarVO> list = null;
        if (vo != null)
            list = ListUtil.toList(vo);
        return success(list);//暂处理为返回数组
    }

    /**
     * 添加司机资质
     * @param param
     * @return
     */
    @PostMapping("/add/certificate")
    private DefaultVO driverAddCertificate(@RequestBody @Valid DriverAddCertificateParam param){
        return success(ListUtil.toList(driverBiz.driverAddCertificate(param)));//暂处理为返回数组
    }

    /**
     * 司机编辑查询
     * @param param
     * @return
     */
    @PostMapping("/save/select")
    private DefaultVO driverEditSelect(@RequestBody Map<String,String> param){
        String idDriver=param.get("idDriver");
        String moduleName=param.get("moduleName");
        if (StrUtil.isEmpty(idDriver))
            throw new BusinessException(4001,"司机ID[idDriver]不能为空");
        if (StrUtil.isEmpty(moduleName))
            throw new BusinessException(4001,"查询模块名[moduleName]不能为空");
        return success(driverBiz.driverEditSelect(idDriver,moduleName));
    }

    /**
     * 获取司机信息
     * @param param
     * @return
     */
    @PostMapping("/info")
    private DefaultVO driverInfo(@RequestBody Map<String,String> param){
        String idDriver = param.get("idDriver");
        if (StrUtil.isEmpty(idDriver))
            throw new BusinessException(4001,"司机ID[idDriver]不能为空");
        return success(driverBiz.getDriverInfoByDriverId(idDriver));
    }

    /**
     * 提现账号保存
     * @param param
     * @return
     */
    @PostMapping("/save/account")
    private DefaultVO driverSaveAccount(@RequestBody @Valid SaveAccountParam param){
        if (StringUtil.isNotBlank(param.getIdWithdrawDepositAccount()))
            throw new BusinessException(4001,"司机提现账户不能随意修改，要修改请联系管理员。");
        return success(driverBiz.driverSaveAccount(param));
    }

    /**
     * 封禁/解封司机
     * @param param
     * @return
     */
    @PostMapping("/status/toggle")
    private DefaultVO driverStatusToggle(@RequestBody Map<String,String> param){
        String idDriver = param.get("idDriver");
        if (StrUtil.isEmpty(idDriver))
            throw new BusinessException(4001,"司机ID[idDriver]不能为空");
        return success(driverBiz.driverStatusToggle(idDriver));
    }

    /**
     * 联想查询车牌号
     * @param param
     * @return
     */
    @PostMapping("/associate/vehicle")
    private DefaultVO driverAssociateVehicle(@RequestBody Map<String,String> param){
        String idFranchisee = param.get("idFranchisee");
        String str = param.get("str");
        if (StrUtil.isEmpty(idFranchisee))
            throw new BusinessException(4001,"运营商ID[idFranchisee]不能为空");
        if (StrUtil.isEmpty(str))
            throw new BusinessException(4001,"关键字[str]不能为空");
        return success(driverBiz.driverAssociateVehicle(idFranchisee,str));
    }

    /**
     * 司机图片本地上传
     * @return
     */
    @PostMapping("/uploadImage")
    private DefaultVO uploadImage(@RequestParam("type")int type, @RequestParam("file") MultipartFile multipartFile) {
        // String subPath;
        // if (StrUtil.isEmpty(subPath = param.get("subPath")))throw new BusinessException(4003,"图片路径[subPath]不能为空");
        String subPath = Constants.Image_Path_Type.get(type);
        if (multipartFile.isEmpty()) {
            throw new BusinessException(4001,"参数异常，文件内容异常。");
        }
        // 当文件超过设置的大小时2M暂定，则不运行上传
        if (multipartFile.getSize() > Constants.FILE_SIZE) {
            throw new BusinessException(4001,"文件异常，文件过大。");
        }
        // 获取文件名后缀
        String OriginalFilename = multipartFile.getOriginalFilename();
        String fileSuffix = OriginalFilename.substring(OriginalFilename.lastIndexOf(".") + 1).toLowerCase();

        String newFileName = new Date().getTime() + ".";

        newFileName += fileSuffix; // 追加后缀
        newFileName = subPath + "/" + newFileName;
        // 判断该类型的文件是否在允许上传的文件类型内
        if (!Arrays.asList(Constants.TYPE_MAP.get("image").split(",")).contains(fileSuffix)) {
            throw new BusinessException(4001,"图片路径[subPath]不能为空");
        }
        DefaultPutRet updRet = uploadService.uploadImage(newFileName, multipartFile);

        return success(updRet);
    }

    /**
     * 刷新司机任务信息
     * @param param
     * @return
     */
    @PostMapping("/job/refresh")
    private DefaultVO ResetDriverTask(@RequestBody @Valid Map<String,String> param){
        String idDriver = param.get("idDriver");
        if (StrUtil.isEmpty(idDriver))
            throw new BusinessException(4001,"司机ID[idDriver]不能为空");
        return success(jobPlatformBiz.refreshDriverJob(idDriver));
    }

    /**
     * 创建司机二维码
     * @param param
     * @return
     */
    @PostMapping("/createQrCode")
    private DefaultVO createDriverQrCode(@RequestBody @Valid Map<String,String> param){
        String idDriver = param.get("idDriver");
        if (StrUtil.isEmpty(idDriver))
            throw new BusinessException(4001,"司机ID[idDriver]不能为空");

//        byte[] qrCode = miniProgramBiz.createDriverQrCode(idDriver);
//        //司机二维码保存路径
//        String subPath = Constants.Image_Path_Type.get(7);
//        String newFileName = new Date().getTime() + ".png";
//        newFileName = subPath + "/" + newFileName;
//
//        DefaultPutRet updRet = uploadService.uploadImageByBytes(newFileName, qrCode);

        return success(driverBiz.createFileDriverQrCode(idDriver));
    }

}
